<?php
namespace app\common\service;


class Config
{
    public function set(Array $formData, Array $field = []){

        if (!is_array($formData)){
            return false;
        }



        $keys = array_keys($formData);

        $model = new \app\common\models\Config();
        $keyDataList = $model->getMany(['status'=>1,'key'=>['in',$keys]])->toArray();
        $modelKeys = [];

        if (!empty($keyDataList)){
            $modelKeys =  array_column($keyDataList,'key');
        }

        foreach ($formData as $k=>$v){
            if (!empty($field) && !in_array($k,$field)){
                continue;
            }
            if (in_array($k,$modelKeys)){
                //更新
                $model->where('key',$k)->update(['value'=>$v]);
            }else{
                //新增
                $model->addDataByField(['key'=>$k,'value'=>$v]);
            }
        }
        return true;
    }
    
    public function get($key){

        $model = new \app\common\models\Config();

        $data = $model->getOne(['status'=>1,'key'=>$key]);

        if (is_null($data)){
            return null;
        }
        $data = $data->toArray();

        return $data['value'];
    }

    public function getMany(Array $key){

        $model = new \app\common\models\Config();

        if (empty($key)){
            return [];
        }

        $data = $model->getMany(['status'=>1,'key'=>['in',$key]])->toArray();

        $return = [];

        foreach ($data as $v){
            $return[$v['key']] = $v['value'];
        }

        foreach ($key as $v){
            if (!isset($return[$v])){
                $return[$v] = '';
            }
        }

        return $return;

    }


}